const app = getApp();
const api = require('../../../ws_micro_shop/utils/api.js');
const {  throttle } = require('../../common/utils/util');
const { qyWXCheckSeesion } = require('../../../common/utils/ws/ws-wxwork');


Page({
  data: {
    pageLoading: false,
    tasks: [],
    personalResult: {},
    impersonalpersonal: {},
    personalTime: 'day_info',
    impersonalTime: 'day_info',
    isQrCode: false,
    taskList: [
      {
        name: '拉新会员',
        title: '拉新',
        attr: 'new_member',
      },
    ],
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-15.png',
      text: '您还不是导购员',
      name: '返回首页',
      url: '',
    },
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    windowHeight: wx.systemInfo.windowHeight,
  },

  onShow() {
    let that = this;
    let access_token = wx.getStorageSync('access_token');

    if (access_token && app.isWXWork) {
      app.qyLogin({
        success: () => {
          that.init();
        },
        fail: err => {
          console.log('企业微信登录失败', err);
        },
      });
    } else {
      app.ws_micro_shoplogin().then(res => {
        that.init();
      });
    }
  },

  onPullDownRefresh() {
    wx.showLoading({
      title: '正在加载',
    });
    wx.showNavigationBarLoading();
    this.onShow();
    setTimeout(function () {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
      wx.hideLoading();
    }, 1500);
  },
  
  init() {
    let that = this;
    let { isSaas } = app.ws_micro_shop_globalData;
    let corpid = wx.getStorageSync('corpid');
    let userid = wx.getStorageSync('cor_userid');
    that.setData({
      isSaas,
      corpid,
      userid,
    })
    
    this.getJobResult();
  },

  getJobResult() {
    let that = this;
    let data = {};
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    !that.data.isSaas && (data = {
      shop_id: 0
    })
    app.ws_micro_shoprequest({
      url: api.staff.index,
      data,
      success: res => {
        if (res && res.code === 0 && res.data) {
          that.setData(res.data);
          app.ws_micro_shop_globalData.shopid = res.data.shop_id || 0;
          app.ws_micro_shop_globalData.guide_id = res.data.guide_id;
          app.ws_micro_shop_globalData.openid = res.data.open_id;
          app.ws_micro_shop_globalData.role = res.data.role;
          if (!that.data.isSaas) {
            if (app.ws_micro_shop_globalData.avatar_url) {
              that.setData({
                avatar_url: app.ws_micro_shop_globalData.avatar_url
              })
            } else {
              wx.qy.getAvatar ({
                success: function(res) {
                  let avatar = res.avatar
                  app.ws_micro_shop_globalData.avatar_url = avatar;
                  that.setData({
                    avatar_url: avatar
                  })
                },
                fail: function(res) {
                  console.log('----------获取头像失败------------', res);                  
                }
              })
            }
          }
        }
        if (res.code === 1) {
          this.toHome();
          return;
        }
      },
      complete: res => {
        this.setData({
          pageLoading: true,
        },() => {
          wx.hideLoading();
        })
      },
    });
  },
  
  showTip(e) {
    let status = Number(e.currentTarget.dataset.status);
    let { role } = this.data;
    let content = '导购分享商品后，客户通过分享进入到商城购买该商品，商品金额会计入到销售额里面。';
    if (role == -1) {
      content = '导购分享被用户购买，商品的金额会被计入到销售额。';
    }
    let title = '销售额说明';
    if (status === 1) {
      content = '1.导购分享海报后，用户扫描二维码就会成为我的客户，计入到新会员。2.后台管理员把散客分配给我，也会计入新会员。';
      if (role == -1) {
        content = '新用户扫描海报和散客被分配，会计入到新会员。';
      }
      title = '新会员说明';
    }

    wx.showModal({
      title,
      content,
      showCancel: false,
      confirmColor: '#4185F4',
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  toggleTime(e) {
    const { time = '', type = '' } = e.currentTarget.dataset;
    this.setData(
      {
        [type]: time,
      }
    );
  },

  onEncoded() {
    let erweima = wx.getStorageSync('qrCode') || '';
    if (app.isWXWork && erweima === '') {
      qyWXCheckSeesion({
        success: () => {
          wx.qy.getQrCode({
            success: (res) => {
              let qrCode = res.qrCode;
              this.setData({
                isQrCode: true,
                qrCode,
              });
              console.log('erweima', qrCode);
              wx.setStorageSync('qrCode', qrCode);
            },
            fail: (res) => {
              wx.showToast({
                title: res.errMsg,
                icon: 'none'
              })
              console.log('企业微信个人二维码获取失败', res);
            },
          });
        },
        fail: () => {
          console.log('企业微信登录失败');
        },
      });
    } else if (app.isWXWork && erweima !== '') {
      let qrCode = erweima;
      this.setData({
        isQrCode: true,
        qrCode,
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '请从企业微信端打开工作台',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定');
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        },
      });
    }
  },

  onScan() {
    wx.scanCode({
      success(res) {
        console.log(res);
      },
    });
  },

  onNavigate:throttle(function(e) {
    const { url = '', ...params } = e.currentTarget.dataset;
    let appId = wx.getStorageSync('appid');
    if (url === 'ws_micro_shop/pages/index/index' && !this.data.isSaas) {
      url = url + '?shopid=' + app.ws_micro_shop_globalData.shopid;
      wx.navigateToMiniProgram({
        appId,
        path: url,
        envVersion: 'release',
        success(res) {
          // 打开成功
          console.info('-------打开成功--------');
        }
      })
    } else {
      url && app.util.navigateTo(url, params);
    }
  }),

  onQrCodeMask() {
    const { isQrCode } = this.data;
    this.setData({
      isQrCode: !isQrCode,
    });
  },

  onCollectFormId(e) {
    app.collectFormId(e);
  },

  onHide() {
    app.util.sendBindInfo(this.data);
  },

  onUnload() {
    app.util.sendBindInfo(this.data);
  },

  toHome() {
    let appJson = app.siteInfo.appJson[app.tabbarindex || 0];
    const url = appJson.homePage || (appJson.tabBar && appJson.tabBar.list && appJson.tabBar.list[0].pagePath);
    app.ws_micro_shop_globalData.isFromB = true;
    app.util.navigateTo(url, {}, 'all');
  },
});
